package com.shroo8.footballblog.controllers.twitter;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.auth.RequestToken;

@Controller
public class CallbackController {

	private static final Logger logger = LoggerFactory.getLogger(SigninController.class);
	
	/*TO DO:
	 * 1. Login Failure: need to handle when the user rejects allowing the app to use his information or if he cancels/fails 
	 * to login at the twitter login page (the exception occurs in the try catch block)
	 * */
	@RequestMapping(value = "/callback", method = RequestMethod.GET)
	public void redirectToHome(Locale locale, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		logger.info("Welcome to twitter callback! The client locale is {}.", locale);
		
		Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
		String redirectUrl = (String) request.getSession().getAttribute("redirectUrl");
        RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
        String verifier = request.getParameter("oauth_verifier");
        try {
            twitter.getOAuthAccessToken(requestToken, verifier);
            request.getSession().removeAttribute("requestToken");
        } catch (TwitterException e) {
            throw new ServletException(e);
        }
        
        logger.info("the redirect url is: "+request.getContextPath() + redirectUrl);
        response.sendRedirect(request.getContextPath() + redirectUrl);
	}

}
